package karaokit.com;

import java.io.File;
import java.io.IOException;

import karaokit.com.KaraoKitEngine.SearchType;

import org.farng.mp3.id3.ID3v1;

import android.app.Activity;
import android.app.Dialog;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;

public class Player extends Activity {

	private static KaraoKitEngine KarEngine = KaraoKitEngine.GetEngine();

	private MediaPlayer mPlayer;
	private MediaController mController;
	private TextView mLyricsTextView;
	private LyricsSynconizer mLyricsSyncronizer;
	private static final int SYNC_DIFF = 200;	
	private static final int LOAD_LYRICS = Menu.FIRST + 1;
	private static final int SYNC_LYRICS = Menu.FIRST + 2;
	private boolean haveLyrics = false;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.play_page);
		mLyricsTextView = (TextView)Player.this.findViewById(R.id.Lyrics);
		//mLyricsTextView.setTypeface(Typeface.createFromAsset(getAssets(), KaraoKitEngine.KaraoKitDir+"lucida.TTF"));
		mPlayer = new MediaPlayer();
		mController = new MediaController(this, false);
		mController.setMediaPlayer(PlayerInterface);
		mController.setPrevNextListeners(NextListener, PrevListener);
		mController.setEnabled(true);
		mController.setAnchorView(this.findViewById(R.id.barContainer));
		
		showMediaProperties();
		haveLyrics = KarEngine.isLyricsLoaded();
		startPlay();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		mController.show(10000);
		return super.onTouchEvent(event);
	}
		
	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		menu.setGroupVisible(1, KaraoKitEngine.GetEngine().isLyricsLoaded());
		return super.onMenuOpened(featureId, menu);
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, LOAD_LYRICS, 0, "Load Lyrics");
		menu.add(1, SYNC_LYRICS, 0, "Sync Lyrics");		
		return true;
	}
	
	private View.OnClickListener fasterLyrics = new
	View.OnClickListener() {		
		public void onClick(View v) {
			mLyricsSyncronizer.setSyncDiff(mLyricsSyncronizer.getSyncDiff()+SYNC_DIFF);
		}
	};

	private View.OnClickListener slowerLyrics = new
	View.OnClickListener() {		
		public void onClick(View v) {
			mLyricsSyncronizer.setSyncDiff(mLyricsSyncronizer.getSyncDiff()-SYNC_DIFF);
		}
	};

	private View.OnClickListener resetLyrics = new
	View.OnClickListener() {		
		public void onClick(View v) {
			mLyricsSyncronizer.setSyncDiff(0);
		}
	};

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId())
		{
		case SYNC_LYRICS: 
			Dialog dialog = new Dialog(this);
			dialog.setContentView(R.layout.sync);
			dialog.setTitle("Sync Lyric with song:");
			(dialog.findViewById(R.id.EndButton)).setOnClickListener(new EndListener(dialog));
			(dialog.findViewById(R.id.PlusButton2)).setOnClickListener(fasterLyrics);
			(dialog.findViewById(R.id.MinusButton)).setOnClickListener(slowerLyrics);
			(dialog.findViewById(R.id.ResetButton)).setOnClickListener(resetLyrics);
			dialog.show(); 
			break;
		case LOAD_LYRICS:
			KaraoKitEngine.GetEngine().startBrowse(this, SearchType.Lyrics);
			finish();
			break;
		}
		return true;
	}

	protected class EndListener implements OnClickListener {
		private Dialog dialog;
		public EndListener(Dialog dialog) {
			this.dialog = dialog;
		}
		public void onClick(View v) {
			dialog.dismiss();
		}
	} 

	private void ChangeMediaFileHelper(File file){
		mPlayer.stop();
		KarEngine.setCurMediaFile(file);
		if (haveLyrics)
		{
			File[] files = file.getParentFile().listFiles(KaraoKitEngine.LyricsFilter);
			int index = KaraoKitEngine.FindLyricsFileIndexByCurrentMediaFile(file.getParentFile());
			if (index > -1)
			{
			KarEngine.setCurLyrics(files[index]);
			}
			else
			{
				KarEngine.setCurLyrics(null);
			}
			
		}
		showMediaProperties();
		startPlay();

	}
	
	private View.OnClickListener NextListener = new
	View.OnClickListener() {		
		public void onClick(View v) {
			ChangeMediaFileHelper(KarEngine.getNextMediaFile());
		}
	};

	private View.OnClickListener PrevListener = new
	View.OnClickListener() {
		public void onClick(View v) {
			ChangeMediaFileHelper(KarEngine.getPrevMediaFile());	
		}
	};

	private MediaController.MediaPlayerControl PlayerInterface = new
	MediaController.MediaPlayerControl() {
		public int getBufferPercentage() {
			return 100;
		}
		public int getCurrentPosition() {
			return mPlayer.getCurrentPosition();
		}
		public int getDuration() {
			return mPlayer.getDuration();
		}
		public boolean isPlaying() {
			return mPlayer.isPlaying();
		}
		public void pause() {
			mPlayer.pause();			
		}
		public void seekTo(int pos) {
			mPlayer.seekTo(pos);			
		}
		public void start() {
			if (KarEngine.isLyricsLoaded()){ 
				mLyricsSyncronizer = new LyricsSynconizer(mPlayer, KarEngine.getCurLyrics(), mLyricsTextView);
				mPlayer.start();
				mLyricsSyncronizer.start();	
			}
			else {
				mPlayer.start();
			}
		}
	};
	

	private void startPlay() {		
		mPlayer.reset();
		mPlayer.setOnCompletionListener(new OnCompletionListener() {
			
			@Override
			public void onCompletion(MediaPlayer mp) {
				ChangeMediaFileHelper(KarEngine.getNextMediaFile());
				
			}});
		try {
			Toast.makeText(this, "Now playing:\n" + KarEngine.getCurMediaFile().getName(), Toast.LENGTH_SHORT).show();
			mPlayer.setDataSource(KarEngine.getCurMediaFile().getAbsolutePath());
			mPlayer.prepare();					
			if (KarEngine.isLyricsLoaded()) {
				Toast.makeText(this, "Lyrics: On", Toast.LENGTH_SHORT).show();				
				mLyricsSyncronizer = new LyricsSynconizer(mPlayer, KarEngine.getCurLyrics(), mLyricsTextView);
				mPlayer.start();
				mLyricsSyncronizer.start();				

			} else {
				Toast.makeText(this, "Lyrics: Off", Toast.LENGTH_SHORT).show();
				String fileName = KarEngine.getCurMediaFile().getName();
				mLyricsTextView.setText("Playing (No Lyrics):\n" + fileName.substring(0,fileName.lastIndexOf(".")));
				mPlayer.start();
			}
		} catch (IOException e) {
			Log.e("Error opening sound file ", e.getMessage());
		}
	}

	private void showMediaProperties() {
		ID3v1 prop = KarEngine.getMediaProperties();
		if (prop != null) {
			TextView tv = (TextView) this.findViewById(R.id.AlbumName);
			tv.setText(prop.getAlbum());
			tv = (TextView) this.findViewById(R.id.ArtistName);
			tv.setText(prop.getArtist());
			tv = (TextView) this.findViewById(R.id.SongName);
			tv.setText(prop.getSongTitle());
		}	
		else
		{
			TextView tv = (TextView) this.findViewById(R.id.AlbumName);
			tv.setText("No Info Available");
			tv = (TextView) this.findViewById(R.id.ArtistName);
			tv.setText("No Info Available");
			tv = (TextView) this.findViewById(R.id.SongName);
			tv.setText("No Info Available");
		}
	}
	
	

	@Override
	protected void onDestroy() {		
		if (mPlayer != null)
			mPlayer.stop();
		//KarEngine.setSearchType(SearchType.Media);
		super.onDestroy();
	}
}